Skip to main content

Leetcode 399

· 2 min read
Junhe Chen
class Solution {
public double[] calcEquation(List<List<String>> equations, double[] values, List<List<String>> queries) {
// to solve this question
// we first wanna to think this as a graph and using dfs find the path from a to b
// in order to do so ,
// we must construct a weighted graph
HashMap<String,HashMap<String,Double>> graph = new HashMap<>();

// we need to get equations to gain our two string node
// we also need to have a index to keep track
int index = 0;
for(List<String> e : equations){
String a = e.get(0);
String b = e.get(1);

graph.putIfAbsent(a,new HashMap<>());
graph.putIfAbsent(b,new HashMap<>());


graph.get(a).put(b,values[index]);
graph.get(b).put(a,1 / values[index]);
index ++;

graph.get(a).put(a,1.0);
graph.get(b).put(b,1.0);

}
// we have sucessfully build our graph
// lets look at our queiries
double [] ans = new double[queries.size()];
Arrays.fill(ans,-1.0);
for(int i = 0; i < queries.size(); i ++){
List<String> q = queries.get(i);
String start = q.get(0);
String end = q.get(1);

// check if start and end in the graph at all
if(!graph.containsKey(start) || !graph.containsKey(end)){
continue;
}else {
dfs(graph,start,end,new HashSet<String>(),1.0,ans,i);

continue;
}
}
return ans;
}
// let's make our dfs method
private void dfs (HashMap<String,HashMap<String,Double>> graph, String start, String end, Set<String> visited, double pre, double[] ans, int index){
visited.add(start);
if(graph.get(start).containsKey(end)){
ans[index] = graph.get(start).get(end) * pre;
}

for(String next : graph.get(start).keySet()){
if (visited.contains(next)) continue;
dfs(graph,next,end,visited,graph.get(start).get(next) * pre ,ans,index);
}
}
}